from util.Route import *
from service import UserManageService,RoleManageService
from datetime import datetime
import hashlib
import os  
import time

# 查询所有用户信息（分页）
@route("/user/get/all",methods = ['POST'])
def userGetAll():
    data = request.json
    page= data.get("page")
    cdn = data.get("cdn")
    page = Page(num=page['num'], size=page['size'])  # Create a Page object
    r = UserManageService.getUserAll(page,cdn)
    return R.success(r)

# 根据用户id查询用户信息
@route("/user/get/info")
def userGetInfo():
    id = request.args.get("id")  # Create a Page object
    r = UserManageService.getUserInfo(id)
    return R.success(r)

# 获取用户自己的信息
@route("/user/get/my_info")
def userGetMyInfo():
    uid = getUid()
    r = UserManageService.getUserInfo(uid)
    return R.success(r)

# 获取用户的角色列表
@route("/user/get/my_roles_name")
def getMyRolesName():
    uid = getUid()
    r = UserManageService.getUserRolesName(uid)
    return R.success(r)
# 用户获取自己菜单
@route("/user/get/my_menus")
def getMyMenus():
    uid = getUid()
    rid = getRid()
    r = UserManageService.getUserMenusByUidAndRid(uid,rid)
    return R.success(r)
# 用户获取自己的菜单按钮
@route("/user/get_my_menu_handle" )
def getMyMenuHandle():
    uid = getUid()
    rid = getRid()
    r = UserManageService.getUserMenuHandle(uid,rid)
    return R.success(r)

# 根据用户id查询用户状态
@route("/user/get/status")
def userGetStatus():
    uid = request.args.get('uid') 
    r = UserManageService.getUserStatus(uid)
    return R.success(r)

# 添加用户
@route("/user/add", methods=['POST'])
def userAdd():
    data = request.json
    r = UserManageService.addUser(data)
    username = data['username']
    if r == True:
        return R.success(r, "用户添加成功")
    elif r == 2 :
        return R.bad_request('用户:'+username+' 已存在')
    elif r == 3 :
        return R.bad_request('用户名:'+username+' 长度错误')
    else:
        return R.create(400, None, '用户添加失败')

# 修改用户信息(nickname,sex,head...)
@route("/user/update", methods = ['POST'])
def userUpdate():
    r = UserManageService.updateUser(request.json)
    if r:
        return R.success(r,"用户信息修改成功")
    else:
        return R.create(400,None,'用户信息修改失败')
    
# 用户修改自己的信息
@route("/user/update/self", methods = ['POST'])
def userUpdateSelf():
    uid = getUid()
    info = request.json
    info['uId'] = uid
    info = formatParam(info,['status','head'])
    r = UserManageService.updateUser(info)
    if r:
        return R.success(r,"用户信息修改成功")
    else:
        return R.create(400,None,'用户信息修改失败')

# 用户修改密码
@route("/user/update/pwd", methods = ['POST'])
def userUpdatePassword():
    id = getUid()
    r = UserManageService.updatePwd(id,request.json)
    if r == True:
        return R.success('ok','密码修改成功')
    elif r == 2:
        return R.bad_request('原密码错误')
    elif r == 3:
        return R.bad_request('密码的长度不能低于8位')
    return R.bad_request('密码修改失败')
    
# 修改用户密码
@route("/user/reset/pwd", methods = ['POST'])
def surperUserUpdatePassword():
    k:dict = request.json
    password = k["pwd"]
    id = k["id"]
    r = UserManageService.resetPwd(id,password)
    if r:
        return R.success('ok','密码修改成功')
    return R.bad_request('密码修改失败')
    
#删除用户  
@route("/user/del" , methods = ['POST'])
def userDelete():
    uids = request.json
    r = UserManageService.delUser(uids)
    if r:
        return R.success(None,"用户删除成功")
    else:
        return R.create(400,None,'用户删除失败')

# 查看用户拥有的角色
@route("/user/get/roles")
def userGetRoles():
    uid = request.args.get("uid")  # Create a Page object
    r = UserManageService.getUserRolesName(uid)
    return R.success(r)

# 用户获取自己的角色
@route("/user/get_my_roles")
def userGetMyRoles():
    uid = request.environ.get("UID")
    r = UserManageService.getUserRoles(uid)
    return R.success(r)

# 更新用户的角色
@route("/user/role/update", methods = ['POST'])
def userRoleUpdate():
    body = request.json
    r = UserManageService.uploadUserRoles(body['uid'],body['rids'])
    if r :
        return R.success('ok','操作成功')
    return R.bad_request('修改失败')

# 启用和禁用某用户
@route("/user/update/status")
def userUpdateStatus():
    id:int = request.args.get("uid")
    k = request.json
    keys_to_remove = ['uId','username','password','initTime','nickname','email','head','sex','phone']
    k = {key: value for key, value in k.items() if key not in keys_to_remove}
    r = UserManageService.userUpdateStatus(id,k)
    if r:
        return R.success(r)
    else:
        return R.create(400,None)

# 上传用户头像
@route("/user/update/head")
def userUpdateHead():
    uid = request.environ.get("UID")
    # 获取用户上传的头像文件
    head = request.files.get('head')
    if head:
        # 生成时间戳作为文件名
        timestamp = int(time.time())
        file_extension = os.path.splitext(head.filename)[1]  # 保留原始文件扩展名
        filename = f"{timestamp}{file_extension}"
        filepath1 = os.path.join('public', 'head', filename)
        head.save(filepath1)
        # 更新用户表中的头像字段
        # 构建完整的文件路径
        base_url = request.url_root  # 获取当前请求的URL前缀
        filepath2 = f"{base_url}public/head/{filename}"
        r = UserManageService.userUpdateHead(uid, filepath2) 
    if r:
        return R.success(r)
    else:
        return R.create(400,None)